<template>
  <div class="my-page" :class="{ 'dark-mode': isDarkMode }">
    <div class="header">
      <div class="more-icon-container" v-if="isLoggedIn" @click="handleMoreClick">
        <van-icon name="setting-o" class="more-icon" />
      </div>
    </div>

    <div class="content" @click="handleContentClick">
      <div class="login-section" @click.stop="handleLogin">
        <div class="avatar-container" :style="isLoggedIn ? { backgroundImage: `url(${userAvatar})` } : {}">
          <van-icon v-if="!isLoggedIn" name="eye-o" class="eye-icon" />
        </div>
        <p class="login-tip">{{ isLoggedIn ? userName : '点击登录即可评论及发布内容' }}</p>
      </div>

      <div class="action-buttons">
        <div class="action-btn" @click="handleFavorite">
          <van-icon name="star-o" class="btn-icon" />
          <span class="btn-text">收藏</span>
        </div>
        <div class="divider"></div>
        <div class="action-btn" @click="handleCache">
          <van-icon name="back-top" class="btn-icon" style="transform: rotate(180deg);" />
          <span class="btn-text">缓存</span>
        </div>
      </div>

      <div class="menu-list">
        <div class="menu-item" v-for="item in menuItems" :key="item.key" @click="handleMenuClick(item)">
          <van-icon :name="item.icon" class="menu-icon" />
          <span class="menu-text">{{ item.label }}</span>
          <van-icon name="arrow" class="arrow-icon" />
        </div>
      </div>
    </div>

    <!-- 登录注册组件 -->
    <LoginRegister ref="loginRegisterRef" />

    <!-- 编辑资料组件 -->
    <EditProfile ref="editProfileRef" @update="handleUserInfoUpdate" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { showToast } from 'vant';
import { useDarkModeStore } from '@/stores/darkMode';
import LoginRegister from '../components/LoginRegister.vue';
import EditProfile from '../components/EditProfile.vue';
import defaultAvatar from '@/assets/img/my/user-avatar.jpg';

const router = useRouter();
const darkModeStore = useDarkModeStore();
const isDarkMode = computed(() => darkModeStore.isDarkMode);
const loginRegisterRef = ref<InstanceType<typeof LoginRegister> | null>(null);
const editProfileRef = ref<InstanceType<typeof EditProfile> | null>(null);

// 登录状态
const isLoggedIn = ref(false);

// 用户信息
const userAvatar = ref(defaultAvatar);
const userName = ref('');

// 菜单项数据
const menuItems = ref([
  { key: 'follow', label: '我的关注', icon: 'like-o' },
  { key: 'history', label: '观看记录', icon: 'clock-o' },
  { key: 'contribute', label: '我要投稿', icon: 'plus' },
  { key: 'feedback', label: '意见反馈', icon: 'chat-o' },
  { key: 'disclaimer', label: '免责声明', icon: 'info-o' }
]);

// 获取默认昵称（用户+手机号后四位）
const getDefaultNickname = (phoneNumber: string) => {
  const lastFour = phoneNumber.slice(-4);
  return `用户${lastFour}`;
};

// 加载用户数据
const loadUserData = () => {
  const currentPhone = localStorage.getItem('currentPhoneNumber');
  if (!currentPhone) {
    isLoggedIn.value = false;
    userName.value = '';
    userAvatar.value = defaultAvatar;
    return;
  }

  const users = JSON.parse(localStorage.getItem('users') || '[]');
  const user = users.find((u: any) => u.phoneNumber === currentPhone);

  if (user) {
    // 如果有昵称，使用存储的昵称，否则使用默认昵称
    userName.value = user.nickname || getDefaultNickname(currentPhone);

    // 如果有头像，使用存储的头像，否则使用默认头像
    if (user.avatar) {
      userAvatar.value = user.avatar;
    } else {
      userAvatar.value = defaultAvatar;
    }
  } else {
    // 如果没有找到用户，使用默认值
    userName.value = getDefaultNickname(currentPhone);
    userAvatar.value = defaultAvatar;
  }
};

// 检查登录状态
const checkLoginStatus = () => {
  const loggedIn = localStorage.getItem('isLoggedIn') === 'true';
  isLoggedIn.value = loggedIn;
  if (loggedIn) {
    loadUserData();
  } else {
    userName.value = '';
    userAvatar.value = defaultAvatar;
  }
};

// 处理更多选项点击（显示编辑资料）
const handleMoreClick = () => {
  if (isLoggedIn.value && editProfileRef.value) {
    editProfileRef.value.show();
  }
};

// 处理内容区域点击（登录后不弹出登录组件）
const handleContentClick = () => {
  if (!isLoggedIn.value) {
    showLoginRegister();
  }
};

// 处理登录点击
const handleLogin = () => {
  if (!isLoggedIn.value) {
    showLoginRegister();
  }
};

// 显示登录注册组件
const showLoginRegister = () => {
  if (loginRegisterRef.value) {
    loginRegisterRef.value.show(router.currentRoute.value.path);
  }
};

// 处理登录成功
const handleLoginSuccess = () => {
  checkLoginStatus();
};

// 处理用户信息更新
const handleUserInfoUpdate = () => {
  loadUserData();
};

// 处理收藏点击
const handleFavorite = () => {
  // 如果用户未登录，显示登录注册页面
  if (!isLoggedIn.value) {
    showLoginRegister();
    return;
  }
  // 已登录，跳转到收藏页面
  router.push('/favorites');
};

// 处理缓存点击
const handleCache = () => {
  console.log('缓存');
};

// 处理菜单项点击
const handleMenuClick = (item: { key: string; label: string }) => {
  // 如果用户未登录，显示登录注册页面
  if (!isLoggedIn.value) {
    showLoginRegister();
    return;
  }

  // 已登录用户的操作
  if (item.key === 'history') {
    router.push('/watch-history')
  } else if (item.key === 'disclaimer') {
    router.push('/disclaimer')
  } else if (item.key === 'feedback') {
    router.push('/feedback')
  } else if (item.key === 'follow') {
    router.push('/my-follow')
  } else if (item.key === 'contribute') {
    showToast('该功能暂未开放');
  } else {
    console.log('点击菜单:', item.label);
  }
};

// 监听登录成功事件
onMounted(() => {
  checkLoginStatus();
  window.addEventListener('loginSuccess', handleLoginSuccess);
});

onUnmounted(() => {
  window.removeEventListener('loginSuccess', handleLoginSuccess);
});
</script>

<style scoped lang="less">
.my-page {
  width: 100%;
  min-height: 100vh;
  background-color: #fff;
  color: #000;
  display: flex;
  flex-direction: column;
  padding-bottom: 7vh;
  box-sizing: border-box;
  transition: background-color 0.3s ease, color 0.3s ease;

  &.dark-mode {
    background-color: #000;
    color: #fff;
  }
}

.header {
  width: 100%;
  padding: 2vh 4vw 0;
  box-sizing: border-box;
  display: flex;
  justify-content: flex-end;
  align-items: center;

  .more-icon-container {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    background-color: #f5f5f5;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: background-color 0.2s;

    &:active {
      background-color: #e8e8e8;
    }

    .more-icon {
      font-size: 18px;
      color: #999;
    }
  }
}

&.dark-mode .header {
  .more-icon-container {
    background-color: #333;

    &:active {
      background-color: #444;
    }

    .more-icon {
      color: #ccc;
    }
  }
}

.content {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 0 4vw;
  box-sizing: border-box;
}

.login-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;

  .avatar-container {
    height: 8vh;
    aspect-ratio: 1/1;
    border-radius: 50%;
    background-color: #f5f5f5;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 2vh;
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;

    .eye-icon {
      font-size: 20px;
      color: #999;
    }
  }

  .login-tip {
    font-size: 10px;
    color: #333;
    text-align: center;
    margin: 0;
  }
}

.action-buttons {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  margin-top: 4vh;
  margin-bottom: 2vh;

  .action-btn {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    gap: 1vw;

    .btn-icon {
      font-size: 20px;
      color: #333;
    }

    .btn-text {
      font-size: 12px;
      color: #333;
    }
  }

  .divider {
    width: 1px;
    height: 40px;
    background-color: #e5e5e5;
    margin: 0 4vw;
  }
}

.menu-list {
  width: 100%;
  margin-top: 2vh;

  .menu-item {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 2vh 0;
    border-bottom: 1px solid #f5f5f5;
    cursor: pointer;
    transition: background-color 0.2s;

    &:active {
      background-color: #f9f9f9;
    }

    &:last-child {
      border-bottom: none;
    }

    .menu-icon {
      font-size: 16px;
      color: #333;
      margin-right: 12px;
    }

    .menu-text {
      font-size: 12px;
      color: #333;
      flex: 1;
    }

    .arrow-icon {
      font-size: 12px;
      color: #ccc;
    }
  }
}

.my-page.dark-mode {
  .login-section {
    .login-tip {
      color: #fff;
    }
  }

  .action-buttons {
    .action-btn {
      .btn-icon {
        color: #fff;
      }

      .btn-text {
        color: #fff;
      }
    }

    .divider {
      background-color: #444;
    }
  }

  .menu-list {
    .menu-item {
      border-bottom-color: #333;

      &:active {
        background-color: #222;
      }

      .menu-icon {
        color: #fff;
      }

      .menu-text {
        color: #fff;
      }

      .arrow-icon {
        color: #666;
      }
    }
  }
}
</style>
